package bat.ke.qq.com.tx.service.impl;

import bat.ke.qq.com.tx.bean.Account;
import bat.ke.qq.com.tx.dao.AccountMapper;
import bat.ke.qq.com.tx.service.AccountService;
import bat.ke.qq.com.tx.service.TransferRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 *
 *
 *
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private AccountService accountService;

    @Autowired
    private TransferRecordService transferRecordService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transfer(String out, String in, int amount) throws Exception {

        int mark=0;
        try {
            // 转账转入
            inMoney(in,amount);
            // 转账转出
            outMoney(out,amount);

            mark=1;
        } finally {
            transferRecordService.transfer(out,in,amount,mark);
        }
        int i=1/0;
    }

    @Override
    public void outMoney(String out,int amount) throws Exception{

        Account account = accountMapper.getOne(out);

        // 判断余额
        if(account.getBalance()-amount >= 0){
            accountMapper.update(out, account.getBalance()-amount);
        }else {
            throw new Exception("余额不足,转账失败");
        }

    }

    @Override
    public void inMoney(String in,int amount) throws Exception{

        Account account = accountMapper.getOne(in);
        accountMapper.update(in, account.getBalance()+amount);

    }

}
